package com.caochenlei.stack;

public class Stack<E> {
    private E[] elements;   //存放堆栈元素
    private int maxSize;    //存放堆栈大小
    private int top;        //堆栈栈顶指针

    public Stack(int capacity) {
        top = -1;
        maxSize = capacity;
        elements = (E[]) new Object[capacity];
    }

    //判断堆栈是否为空
    public boolean isEmpty() {
        return top == -1;
    }

    //判断堆栈是否已满
    public boolean isFull() {
        return top == maxSize - 1;
    }

    //获取堆栈元素个数
    public int size() {
        return top + 1;
    }

    //进栈操作
    public void push(E element) {
        //判断堆栈是否已满
        if (isFull()) {
            System.out.println("堆栈已满，插入失败：" + element);
            return;
        }
        //进栈操作
        top++;
        elements[top] = element;
    }

    //出栈操作
    public E pop() {
        //判断堆栈是否为空
        if (isEmpty()) {
            System.out.println("堆栈已空，获取失败");
            return null;
        }
        //出栈操作
        E element = elements[top];
        top--;
        return element;
    }

    //查看栈顶
    public E peek() {
        //判断堆栈是否为空
        if (isEmpty()) {
            System.out.println("堆栈已空，获取失败");
            return null;
        }
        //查看栈顶
        return elements[top];
    }

    @Override
    public String toString() {
        //获取堆栈有效元素
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i <= top; i++) {
            sb.append(" " + elements[i] + " ");
        }
        sb.append("]");
        //返回堆栈详细信息
        return "Stack{" +
                "elements=" + sb.toString() +
                ", eleSize=" + size() +
                ", maxSize=" + maxSize +
                ", top=" + top +
                '}';
    }
}
